//
//  OpenUDID+KeyChain.m
//  KLine
//
//  Created by RyanXu on 10/12/15.
//  Copyright © 2018年 123.com.cn. All rights reserved.
//

#import "OpenUDID+KeyChain.h"

static NSString * kOpenUDIDSessionCache = nil;
static NSString *const OPENUDID = @"cn.com.123.OPENUDID";

@implementation OpenUDID(KeyChain)

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service account:(NSString *)acc{
    NSMutableDictionary *dicx = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 (id)kSecClassGenericPassword,(id)kSecClass,
                                 nil];
    if (acc) {
        dicx[(id)kSecAttrAccount]=acc;
    }
    if (service) {
        dicx[(id)kSecAttrService]=service;
    }
    return dicx;
}

+ (void)save:(NSString *)service account:(NSString *)acc data:(NSData *)data
{
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:acc];
    SecItemDelete((CFDictionaryRef)keychainQuery);
    [keychainQuery setObject:data forKey:(id)kSecValueData];
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

+ (void)save:(NSString *)service data:(id)data {
    [[self class] save:service account:service data:data];
}

+ (NSData *)load:(NSString *)service account:(NSString *)acc
{
    NSData *ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:acc];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        ret = [NSData dataWithData:(__bridge NSData *)keyData];
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

+ (NSData *)load:(NSString *)service {
    return [[self class] load:service account:service];
}

+ (void)delete:(NSString *)service {
    return [[self class] delete:service account:service];
}

+ (void)delete:(NSString *)service account:(NSString *)acc
{
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:acc];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}
+(NSString *)valueUseKeyChain
{
    NSData *data =  (NSData *)[OpenUDID load:OPENUDID];
    if (data == nil) {
        kOpenUDIDSessionCache = [OpenUDID value];
        [OpenUDID save:OPENUDID data:[kOpenUDIDSessionCache dataUsingEncoding:NSUTF8StringEncoding]];
    } else {
        kOpenUDIDSessionCache = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return kOpenUDIDSessionCache;
}

@end
